package com.qiyang.converters;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created on 2020/12/11.
 *
 * @author qiyang.
 * 描述：
 */
public class MyStringToDateConverter implements Converter<String, Date> {

    public Date convert(String source) {
        if (!StringUtils.isEmpty(source)) {
            // 既支持yyyy-MM-dd 也支持 yyyy/MM/dd
            try {
                //业务逻辑
                if (source.split("-").length == 3) {
                    System.out.println("自定义类型转换器生效");
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    return df.parse(source);
                } else if (source.split("/").length == 3) {
                    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                    return df.parse(source);
                } else {
                    throw new RuntimeException("日期转换错误 -> " + source);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
